package cn.virens.oauth.request;

import cn.virens.common.exception.APIException;
import cn.virens.common.utils.Assert;
import cn.virens.oauth.request.principal.DelegatePrincipal;
import cn.virens.oauth.subject.Subject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 用户登录信息包装HttpServletRequest类
 *
 * @author virens
 */
public class VirensHttpServletRequest extends HttpServletRequestWrapper {
    private final Subject subject;

    public VirensHttpServletRequest(HttpServletRequest request, Subject subject) {
        super(Assert.isNull(request, "原始请求对象不可为空"));

        // 根据用户信息构建对应的认证令牌
        this.subject = subject;
    }

    /**
     * 检查是否拥有权限(OR)
     */
    public boolean hasPermissions(String... permissions) throws APIException {
        return subject.hasPermissions(permissions);
    }

    /**
     * 检查是否拥有角色(OR)
     */
    public boolean hasRoles(String... roleIdentifiers) throws APIException {
        return subject.hasRoles(roleIdentifiers);
    }

    @Override
    public Object getAttribute(String name) throws APIException {
        if (!"VirensDelegatePrincipal".equals(name)) {
            return super.getAttribute(name);
        } else {
            return getUserPrincipal();
        }
    }

    @Override
    public DelegatePrincipal getUserPrincipal() {
        return subject.delegate();
    }
}
